package com.qd.system.service.station;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cdqidi.constant.ConstantDto;
import com.cdqidi.db.BaseService;
import com.cdqidi.dto.CacheKey;
import com.cdqidi.excel.ExcelExport;
import com.cdqidi.excel.util.ExportPage;
import com.cdqidi.exception.ApiException;
import com.cdqidi.util.RedisTemplateUtil;
import com.qd.common.sys.domain.entity.station.StationOrgAllDTO;
import com.qd.common.sys.domain.entity.station.StationOrgDTO;
import com.qd.system.mapper.StationOrgMapper;
import com.qd.system.model.StationOrg;
import com.qd.system.service.org.OrgService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.*;

import static java.util.stream.Collectors.toList;

/**
 * 岗位组织
 *
 * @author sjk
 */
@RequiredArgsConstructor
@Service
@Slf4j
public class StationOrgService extends BaseService<StationOrgMapper, StationOrg> {

    private static final String PREFIX_ID = "sys_station_org_orgStationId_{0}";
    private static final String PREFIX_UNIQUE_SYS_STATION = "sys_station_org_orgId_{0}_stationId_{1}";

    private final RedisTemplateUtil<StationOrg> redisTemplateUtil;
    private final OrgService orgService;
    private final StationSetService stationSetService;
    @Resource
    private HttpServletResponse response;

    /**
     * 保存
     *
     * @param dto 页面对象
     * @return 页面对象
     */
    @Transactional(rollbackFor = Exception.class)
    public StationOrgDTO save(StationOrgDTO dto) {
        checkMb(dto);
        final StationOrg model = dtoToModel(dto);
        try {
            if (super.save(model)) {
                return modelToDto(model);
            }
            throw new ApiException("添加失败");
        } finally {
            clearCache(model);
            model.freeData();
        }
    }

    /**
     * 修改
     *
     * @param dto 页面对象
     * @return 页面对象
     */
    @Transactional(rollbackFor = Exception.class)
    public StationOrgDTO update(StationOrgDTO dto) {
        checkMb(dto);
        final StationOrg historyModel = Optional.ofNullable(getById(dto.getOrgStationId())).orElseThrow(() -> new ApiException("ID不存在,不能更新"));
        final StationOrg model = dtoToModel(dto);
        try {
            if (super.updateById(model)) {
                return modelToDto(model);
            }
            throw new ApiException("更新失败");
        } finally {
            clearCache(historyModel);
            clearCache(model);
            historyModel.freeData();
            model.freeData();
        }
    }

    /**
     * 批量添加
     *
     * @param mList 数据库对象
     */
    @Transactional(rollbackFor = Exception.class)
    public void saveBatch(List<StationOrg> mList) throws ApiException {
        try {
            if (!super.saveBatch(mList)) {
                throw new ApiException("批量添加失败");
            }
        } finally {
            clearCaches(mList);
        }
    }

    /**
     * 批量更新
     *
     * @param mList 数据库对象
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateBatchIds(List<StationOrg> mList) {
        final List<String> ids = mList.stream().map(StationOrg::getOrgStationId).collect(toList());
        final List<StationOrg> historyModelList = checkIds(ids);
        try {
            if (!super.updateBatchById(mList)) {
                throw new ApiException("批量更新失败");
            }
        } finally {
            clearCaches(historyModelList);
            historyModelList.clear();
            ids.clear();
        }
    }

    /**
     * 删除，单个
     *
     * @param orgStationId 主键
     */
    @Transactional(rollbackFor = Exception.class)
    public void removeById(String orgStationId) {
        final StationOrg model = Optional.ofNullable(getById(orgStationId)).orElseThrow(() -> new ApiException("数据不存在,不能删除"));
        try {
            if (!super.removeById(orgStationId)) {
                throw new ApiException("删除失败");
            }
        } finally {
            clearCache(model);
            model.freeData();
        }
    }

    /**
     * 批量删除
     *
     * @param ids 主键集合
     */
    @Transactional(rollbackFor = Exception.class)
    public void removeBatchIds(List<String> ids) {
        List<StationOrg> historyModelList = checkIds(ids);
        try {
            if (!super.removeByIds(ids)) {
                throw new ApiException("批量删除失败");
            }
        } finally {
            clearCaches(historyModelList);
            historyModelList.clear();
        }
    }

    /**
     * 根据传入对象构建查询参数，判断是否存在
     *
     * @param dto 参数
     * @return 存在为true
     */
    @Transactional(readOnly = true)
    public Boolean isExists(StationOrgDTO dto) {
        final QueryWrapper<StationOrg> queryWrapper = createQueryWrapper(dto);
        final boolean exists = super.count(queryWrapper) > 0;
        queryWrapper.clear();
        return exists;
    }

    /**
     * 根据主键判断数据是否存在
     *
     * @param orgStationId 主键
     * @return 存在为true
     */
    @Transactional(readOnly = true)
    public Boolean isExistsById(String orgStationId) {
        boolean exists = false;
        if (StringUtils.hasLength(orgStationId)) {
            final StationOrg model = getById(orgStationId);
            exists = (null != model);
            if (exists) {
                model.freeData();
            }
        }
        return exists;
    }

    /**
     * 根据主键获取数据
     *
     * @param orgStationId 主键
     * @return 单条记录
     */
    @Transactional(readOnly = true)
    public StationOrg getById(String orgStationId) {
        final String key = RedisTemplateUtil.getRedisCacheKey(PREFIX_ID, orgStationId);
        return redisTemplateUtil.get(new CacheKey().setKey(key).setTimeout(ConstantDto.REDIS_TIME_OUT_DAY), () -> super.getById(orgStationId), StationOrg.class);
    }

    /**
     * 根据主键获取数据
     *
     * @param orgStationId 主键
     * @return 单条记录，转换成页面对象
     */
    @Transactional(readOnly = true)
    public StationOrgDTO getByIdDto(String orgStationId) {
        return Optional.ofNullable(getById(orgStationId)).map(this::modelToDto).orElse(null);
    }

    /**
     * 根据条件查询单条数据
     *
     * @param dto 查询参数
     * @return 单条记录
     */
    @Transactional(readOnly = true)
    public StationOrg getOne(StationOrgDTO dto) {
        final QueryWrapper<StationOrg> queryWrapper = createQueryWrapper(dto);
        StationOrg model = super.getOne(queryWrapper);
        queryWrapper.clear();
        return model;
    }

    /**
     * 根据条件查询单条数据
     *
     * @param dto 查询参数
     * @return 单条记录，转换成页面对象
     */
    @Transactional(readOnly = true)
    public StationOrgDTO getOneDto(StationOrgDTO dto) {
        return Optional.ofNullable(getOne(dto)).map(this::modelToDto).orElse(null);
    }

    /**
     * 根据条件查询列表数据
     *
     * @param dto 查询参数
     * @return 列表数据
     */
    @Transactional(readOnly = true)
    public List<StationOrg> getList(StationOrgDTO dto) {
        final QueryWrapper<StationOrg> queryWrapper = createQueryWrapper(dto);
        final List<StationOrg> list = super.list(queryWrapper);
        queryWrapper.clear();
        return list;
    }

    /**
     * 根据条件查询列表数据
     *
     * @param dto 查询参数
     * @return 列表数据，转换成页面对象
     */
    @Transactional(readOnly = true)
    public List<StationOrgDTO> getListDto(StationOrgDTO dto) {
        return modelToDtoList(getList(dto));
    }

    /**
     * 分页数据
     *
     * @param page 分页对象
     * @param dto  查询参数
     * @return 分页信息
     */
    @Transactional(readOnly = true)
    public IPage<StationOrgDTO> page(Page<StationOrg> page, StationOrgDTO dto) {
        final QueryWrapper<StationOrg> queryWrapper = createQueryWrapper(dto, "sta.");
        final IPage<StationOrgDTO> iPage = baseMapper.page(page, queryWrapper);
        queryWrapper.clear();
        return iPage;
    }

    /**
     * 导出Excel
     *
     * @param query 查询条件
     */
    @Transactional(readOnly = true)
    public void export(StationOrgDTO query) {
        final ExportPage<StationOrg, StationOrgDTO> exportPage = new ExportPage<>();
        try {
            final List<StationOrgDTO> list = exportPage.getAllForPage(page -> page(page, query).getRecords());
            try {
                ExcelExport.downloadExcel(response, StationOrgDTO.class, () -> list);
            } catch (IOException e) {
                log.error("导出失败", e);
                throw new ApiException("导出失败");
            }
        } finally {
            exportPage.freeData();
        }
    }

    /**
     * 根据唯一性索引获得数据
     * <p>
     * param orgId
     * param stationId
     *
     * @return 单条数据
     */
    @Transactional(readOnly = true)
    public StationOrg getUniqueByOrgIdAndStationId(String orgId, String stationId) {
        final QueryWrapper<StationOrg> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("org_id", orgId);
        queryWrapper.eq("station_id", stationId);
        final String key = RedisTemplateUtil.getRedisCacheKey(PREFIX_UNIQUE_SYS_STATION, orgId, stationId);
        final StationOrg model = redisTemplateUtil.get(new CacheKey().setKey(key).setTimeout(ConstantDto.REDIS_TIME_OUT_DAY), () -> super.getOne(queryWrapper, false), StationOrg.class);
        queryWrapper.clear();
        return model;
    }

    public void checkMb(StationOrgDTO dto) {
        orgService.checkId(dto.getOrgId());
        stationSetService.checkId(dto.getStationId());
        checkUnique(dto);
    }

    /**
     * 验证唯一性索引
     *
     * @param dto 页面对象
     */
    private void checkUnique(StationOrgDTO dto) {
        StationOrg model = getUniqueByOrgIdAndStationId(dto.getOrgId(), dto.getStationId());
        if (null != model) {
            checkUnique(dto, model);
        }
    }

    /**
     * 验证唯一性索引
     *
     * @param dto   页面对象
     * @param model 根据约束字段查询出来的数据库对象
     */
    private void checkUnique(StationOrgDTO dto, StationOrg model) {
        if (!StringUtils.hasLength(dto.getOrgStationId())) {
            throw new ApiException("数据已存在，请勿重复添加");
        }
        if (!dto.getOrgStationId().equals(model.getOrgStationId())) {
            throw new ApiException("数据已存在，请勿重复添加");
        }
    }

    /**
     * 清空缓存
     *
     * @param model 数据库对象
     */
    public void clearCache(StationOrg model) {
        if (null == model) {
            return;
        }
        redisTemplateUtil.deleteByKey(RedisTemplateUtil.getRedisCacheKey(PREFIX_ID, model.getOrgStationId()));
        redisTemplateUtil.deleteByKey(RedisTemplateUtil.getRedisCacheKey(PREFIX_UNIQUE_SYS_STATION, model.getOrgId(), model.getStationId()));
    }

    /**
     * 批量清空缓存
     *
     * @param list 数据库对象
     */
    public void clearCaches(List<StationOrg> list) {
        if (null == list || list.isEmpty()) {
            return;
        }
        List<String> ids = list.stream().map(model -> RedisTemplateUtil.getRedisCacheKey(PREFIX_ID, model.getOrgStationId())).collect(toList());
        if (!ids.isEmpty()) {
            redisTemplateUtil.deleteByKey(ids);
            ids.clear();
        }
        List<String> uniqueIds = list.stream().map(model -> RedisTemplateUtil.getRedisCacheKey(PREFIX_UNIQUE_SYS_STATION, model.getOrgId(), model.getStationId())).collect(toList());
        if (!uniqueIds.isEmpty()) {
            redisTemplateUtil.deleteByKey(uniqueIds);
            uniqueIds.clear();
        }
    }

    /**
     * 数据库对象转页面对象
     *
     * @param model 数据库对象
     * @return 页面对象
     */
    public StationOrgDTO modelToDto(StationOrg model) {
        if (null == model) {
            return null;
        }
        final StationOrgDTO dto = new StationOrgDTO();
        dto.setOrgStationId(model.getOrgStationId());
        dto.setOrgId(model.getOrgId());
        dto.setStationId(model.getStationId());
        dto.setAddTime(model.getAddTime());
        buildDisplay(dto);
        return dto;
    }

    /**
     * 页面对象转数据库对象
     *
     * @param dto 页面对象
     * @return 数据库对象
     */
    public StationOrg dtoToModel(StationOrgDTO dto) {
        if (null == dto) {
            return null;
        }
        final StationOrg model = new StationOrg();
        model.setOrgStationId(dto.getOrgStationId());
        model.setOrgId(dto.getOrgId());
        model.setStationId(dto.getStationId());
        model.setAddTime(dto.getAddTime());
        return model;
    }

    /**
     * 码表转换
     *
     * @param dto 页面对象
     */
    public void buildDisplay(StationOrgDTO dto) {
        dto.setOrgIdDisplay(orgService.idToDisplay(dto.getOrgId()));
        dto.setStationIdDisplay(stationSetService.idToDisplay(dto.getStationId()));
    }

    /**
     * 数据库对象转页面对象
     *
     * @param list 数据库对象
     * @return 页面对象
     */
    public List<StationOrgDTO> modelToDtoList(List<StationOrg> list) {
        return Optional.ofNullable(list).orElse(Collections.emptyList()).stream().map(this::modelToDto).collect(toList());
    }

    /**
     * 页面对象转数据库对象
     *
     * @param list 页面对象
     * @return 数据库对象
     */
    public List<StationOrg> dtoToModelList(List<StationOrgDTO> list) {
        return Optional.ofNullable(list).orElse(Collections.emptyList()).stream().map(this::dtoToModel).collect(toList());
    }

    /**
     * 拼装查询参数，除了主键的其他字段会自动加入进来
     *
     * @param dto 查询参数，不为空的属性会被自动加入
     */
    public QueryWrapper<StationOrg> createQueryWrapper(StationOrgDTO dto) {
        return createQueryWrapper(dto, "");
    }

    /**
     * 拼装查询参数，除了主键的其他字段会自动加入进来
     *
     * @param dto        查询参数，不为空的属性会被自动加入
     * @param tableAlias 表别名
     */
    public QueryWrapper<StationOrg> createQueryWrapper(StationOrgDTO dto, String tableAlias) {
        final QueryWrapper<StationOrg> queryWrapper = new QueryWrapper<>();
        if (null != dto) {
            if (StringUtils.hasLength(tableAlias) && tableAlias.charAt(tableAlias.length() - 1) != '.') {
                tableAlias += ".";
            }
            if (StringUtils.hasLength(dto.getOrgId())) {
                queryWrapper.eq(tableAlias + "org_id", dto.getOrgId());
            }
            if (StringUtils.hasLength(dto.getStationId())) {
                queryWrapper.eq(tableAlias + "station_id", dto.getStationId());
            }
            if (StringUtils.hasLength(dto.getBeginTime())) {
                queryWrapper.apply("date_format(" + tableAlias + "add_time,'%Y-%m-%d') >= {0}", dto.getBeginTime());
            }
            if (StringUtils.hasLength(dto.getEndTime())) {
                queryWrapper.apply("date_format(" + tableAlias + "add_time,'%Y-%m-%d') <= {0}", dto.getEndTime());
            }
            if (StringUtils.hasLength(dto.getOrgName())) {
                queryWrapper.like("so.org_name", dto.getOrgName());
            }
            if (StringUtils.hasLength(dto.getStationCode())) {
                queryWrapper.eq("s.station_code", dto.getStationCode());
            }
            if (StringUtils.hasLength(dto.getStationName())) {
                queryWrapper.like("s.station_name", dto.getStationName());
            }
        }
        queryWrapper.orderByAsc("st.idx");
        return queryWrapper;
    }

    /**
     * 批量检查主键在数据库中是否存在
     *
     * @param ids 主键集合
     * @return 主键查询出来的集合
     */
    public List<StationOrg> checkIds(List<String> ids) {
        if (null == ids || ids.isEmpty()) {
            throw new ApiException("ids不能为空");
        }
        final List<StationOrg> list = super.listByIds(ids);
        if (list.isEmpty()) {
            throw new ApiException("ids不存在" + Arrays.toString(ids.toArray()));
        }
        if (ids.size() == list.size()) {
            return list;
        }
        List<String> dbIds = list.stream().map(StationOrg::getOrgStationId).collect(toList());
        final List<String> notExistsList = ids.stream().filter(id -> !dbIds.contains(id)).collect(toList());
        dbIds.clear();
        if (!notExistsList.isEmpty()) {
            throw new ApiException("ids不存在" + Arrays.toString(notExistsList.toArray()));
        }
        return list;
    }

    @Transactional(rollbackFor = Exception.class)
    public void saveAll(StationOrgAllDTO dto) {
        final String stationId = dto.getStationId();
        final List<String> orgIds = dto.getOrgIds();
        List<StationOrg> list = new ArrayList<>(orgIds.size());
        LocalDateTime now = LocalDateTime.now();
        for (String orgId : orgIds) {
            if (null == getUniqueByOrgIdAndStationId(orgId, stationId)) {
                StationOrg data = new StationOrg();
                data.setOrgId(orgId).setStationId(stationId).setAddTime(now);
                list.add(data);
            }
        }
        if (!list.isEmpty()) {
            saveBatch(list);
        }
    }
}